package com.sczmgk.hotline_pzh.utils;

import android.annotation.TargetApi;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.DocumentsContract;
import android.provider.MediaStore;

import com.sczmgk.hotline_pzh.entity.MediaBean;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;


/**
 * 手机媒体库工具
 */
public class ContentUtil {


//    Intent intent=new Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
//    intent.addCategory(Intent.CATEGORY_OPENABLE);
//    intent.setType("image/jpeg");
//    if(android.os.Build.VERSION.SDK_INT>=android.os.Build.VERSION_CODES.KITKAT){isMediaDocument
//    }else{
//        startActivityForResult(intent, SELECT_PIC);
//    }


    private static String TAG = ContentUtil.class.getSimpleName();

    private static String AUDIO = "Audio";
    private static String VIDEO = "Video";

    /**
     * 取得图片的路径
     *
     * @param context
     * @param data
     * @return
     */
    public static String selectImage(Context context, Intent data) {
        Uri selectedImage = data.getData();
//      Log.e(TAG, selectedImage.toString());
        if (selectedImage != null) {
            String uriStr = selectedImage.toString();
            String path = uriStr.substring(10, uriStr.length());
            if (path.startsWith("com.sec.android.gallery3d")) {
                MyLog.e(TAG, "It's auto backup pic path:" + selectedImage.toString());
                return null;
            }
        }
        String[] filePathColumn = {MediaStore.Images.Media.DATA};
        Cursor cursor = context.getContentResolver().query(selectedImage, filePathColumn, null, null, null);
        cursor.moveToFirst();
        int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
        String picturePath = cursor.getString(columnIndex);
        cursor.close();
        return picturePath;
    }

    /**
     * 根据图片的uri取得图片的路径（Android4.4.4 以后的URI做了版本适配)
     *
     * @param context
     * @param uri
     * @return
     */
    @TargetApi(19)
    public static MediaBean getPath(final Context context, final Uri uri) {
        //判断版本是否高于19
        final boolean isKitKat = Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT;
        // DocumentProvider
        if (isKitKat && DocumentsContract.isDocumentUri(context, uri)) {
            MediaBean mediaBean = new MediaBean();
            mediaBean.setType(1);
            MyLog.i(TAG, "isDocumentUri----------");
            // ExternalStorageProvider
            if (isExternalStorageDocument(uri)) {
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                if ("primary".equalsIgnoreCase(type)) {
                    String[] split1 = docId.split("/");
                    String title = split1[split1.length - 1];
                    String path = Environment.getExternalStorageDirectory() + "/" + split[1];
                    File sdPath = new File(path);
                    long size = sdPath.length();
                    mediaBean.setPath(Environment.getExternalStorageDirectory() + "/" + split[1]);
                    mediaBean.setTitle(title);
                    mediaBean.setSize(size);
                    return mediaBean;
                }

                // TODO handle non-primary volumes
            }
            // DownloadsProvider
            else if (isDownloadsDocument(uri)) {
                MyLog.i(TAG, "isDownloadsDocument----------");
                final String id = DocumentsContract.getDocumentId(uri);
                final Uri contentUri = ContentUris.withAppendedId(Uri.parse("content://downloads/public_downloads"), Long.valueOf(id));
                fillMediaBean(mediaBean, context, contentUri, null, null);
                return mediaBean;
            }
            // MediaProvider 原生Android7.0
            else if (isMediaDocument(uri)) {
                MyLog.i(TAG, "isMediaDocument----------");
                final String docId = DocumentsContract.getDocumentId(uri);
                final String[] split = docId.split(":");
                final String type = split[0];
                Uri contentUri = null;
                if ("image".equals(type)) {
                    contentUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
                } else if (VIDEO.equalsIgnoreCase(type)) {
                    contentUri = MediaStore.Video.Media.EXTERNAL_CONTENT_URI;
                } else if (AUDIO.equalsIgnoreCase(type)) {
                    contentUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
                }
                final String selection = "_id=?";
                final String[] selectionArgs = new String[]{split[1]};
                for (int i = 0; i < selectionArgs.length; i++) {
                    String id = selectionArgs[i];
                    MyLog.i(TAG, "媒体--id---是： " + id);
                    mediaBean.setId(id);
                }
                fillMediaBean(mediaBean, context, contentUri, selection, selectionArgs);
                return mediaBean;
            }
        }
        // MediaStore (and general)
        else if ("content".equalsIgnoreCase(uri.getScheme())) {
            MediaBean mediaBean = new MediaBean();
            mediaBean.setType(0);

            // Return the remote address
            if (isGooglePhotosUri(uri)) {
                mediaBean.setPath(uri.getLastPathSegment());
                return mediaBean;
            } else {

                String path = getDataColumn(context, uri, null, null);
                boolean isImage = isImage(path);
                if (isImage){
                    MyToast.show(context , "请选择音视频");
                    return null ;
                }

                fillMediaBean(mediaBean, context, uri, null, null);
                return mediaBean;
            }
        }
        // 原生android自身录制的会走这个方法
        // 小米5.0走这个方法
        else if ("file".equalsIgnoreCase(uri.getScheme())) {
            MediaBean mediaBean = new MediaBean();
            mediaBean.setType(0);
            fillFileBean(mediaBean, context, uri);
            return mediaBean;
        }

        return null;
    }

    private static boolean isImage(String path) {

        File file = new File(path) ;

        if (isJpgFile(file)){
            return true;
        }

        if (isGifFile(file)){
            return true;
        }

        return false ;

    }

    private static void fillFileBean(MediaBean mediaBean, Context context, Uri uri) {
        MediaMetadataRetriever mmr = new MediaMetadataRetriever();
        mmr.setDataSource(uri.getPath());
        String duration = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
        String title = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_TITLE);
        String mimeType = mmr.extractMetadata(MediaMetadataRetriever.METADATA_KEY_MIMETYPE);
        if (title == null) {
            String[] split = uri.getPath().split("/");
            title = split[split.length - 1];
        }

        File file = new File(uri.getPath());
        long size = file.length();
        mediaBean.setSize(size);
        mediaBean.setPath(uri.getPath());
        mediaBean.setDuration(Long.parseLong(duration));
        mediaBean.setTitle(title);
        mediaBean.setMimeType(mimeType);
    }

    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context       The context.
     * @param uri           The Uri to query.
     * @param selection     (Optional) Filter used in the query.
     * @param selectionArgs (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static void fillMediaBean(MediaBean mediaBean, Context context, Uri uri, String selection, String[] selectionArgs) {

        Cursor cursor = null;
        final String path = MediaStore.MediaColumns.DATA;
        final String title = MediaStore.MediaColumns.TITLE;
        final String mimeType = MediaStore.MediaColumns.MIME_TYPE;
        final String size = MediaStore.MediaColumns.SIZE;

//        String duration = null ;
//        if (mediaType.equals(AUDIO)){
        String duration = MediaStore.Audio.Media.DURATION;
//        }else if (mediaType.equals(VIDEO)){
//            duration = MediaStore.Video.Media.DURATION ;
//        }


        final String[] projection = {
                path, title, mimeType, size, duration
        };

//        MyLog.d(TAG , "URI ---------->" + uri.toString());
        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                mediaBean.setPath(cursor.getString(cursor.getColumnIndexOrThrow(path)));
                mediaBean.setMimeType(cursor.getString(cursor.getColumnIndexOrThrow(mimeType)));
                mediaBean.setTitle(cursor.getString(cursor.getColumnIndexOrThrow(title)));
                mediaBean.setSize(cursor.getLong(cursor.getColumnIndexOrThrow(size)));
                mediaBean.setDuration(cursor.getLong(cursor.getColumnIndexOrThrow(duration)));
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }

    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is ExternalStorageProvider.
     */
    public static boolean isExternalStorageDocument(Uri uri) {
        return "com.android.externalstorage.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is DownloadsProvider.
     */
    public static boolean isDownloadsDocument(Uri uri) {
        return "com.android.providers.downloads.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is MediaProvider.
     */
    public static boolean isMediaDocument(Uri uri) {
        return "com.android.providers.media.documents".equals(uri.getAuthority());
    }

    /**
     * @param uri The Uri to check.
     * @return Whether the Uri authority is Google Photos.
     */
    public static boolean isGooglePhotosUri(Uri uri) {
        return "com.google.android.apps.photos.content".equals(uri.getAuthority());
    }

    public static boolean isGifFile(File file) {
        try {
            FileInputStream inputStream = new FileInputStream(file);
            int[] flags = new int[5];
            flags[0] = inputStream.read();
            flags[1] = inputStream.read();
            flags[2] = inputStream.read();
            flags[3] = inputStream.read();
            inputStream.skip(inputStream.available() - 1);
            flags[4] = inputStream.read();
            inputStream.close();
            return flags[0] == 71 && flags[1] == 73 && flags[2] == 70 && flags[3] == 56 && flags[4] == 0x3B;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private static boolean isJpgFile(File file){
        try {
            FileInputStream bin = new FileInputStream(file);
            int b[] = new int[4];
            b[0] = bin.read();
            b[1] = bin.read();
            bin.skip(bin.available() - 2);
            b[2] = bin.read();
            b[3] = bin.read();
            bin.close();
            return b[0] == 255 && b[1] == 216 && b[2] == 255 && b[3] == 217;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }


    /**
     * Get the value of the data column for this Uri. This is useful for
     * MediaStore Uris, and other file-based ContentProviders.
     *
     * @param context
     *            The context.
     * @param uri
     *            The Uri to query.
     * @param selection
     *            (Optional) Filter used in the query.
     * @param selectionArgs
     *            (Optional) Selection arguments used in the query.
     * @return The value of the _data column, which is typically a file path.
     */
    public static String getDataColumn(Context context, Uri uri, String selection,
                                       String[] selectionArgs) {

        Cursor cursor = null;
        final String column = "_data";
        final String[] projection = { column };

        try {
            cursor = context.getContentResolver().query(uri, projection, selection, selectionArgs,
                    null);
            if (cursor != null && cursor.moveToFirst()) {
                final int column_index = cursor.getColumnIndexOrThrow(column);
                return cursor.getString(column_index);
            }
        } finally {
            if (cursor != null)
                cursor.close();
        }
        return null;
    }
}